import React from "react"
import {Button, message, PageHeader, Table} from "antd";
import {ArrowLeftOutlined} from "@ant-design/icons";
import cs from "classnames";
import {Icon as LegacyIcon} from "@ant-design/compatible"
import SearchAutoComplete from "libs/search-auto-complete"
import columns from "./columns"
import {useRequest} from '@umijs/hooks'
import {defaultSize, pageSetting} from "project-config"
import {useTableCheck, formatResult} from "../../shared/libs/hooks/table-hooks"
import "./index.less"
import {get} from "server"
import {del} from "../../shared/server";

const Comment = (props) => {

  //获取数据
  const getPageData = ({current, pageSize, filter, sort, searchKey}) => {
    return get(`/comments/${pageSize}/${current}`, searchKey ? {searchKey} : {})
  }

  //表格选中
  const {rowSelection, ids} = useTableCheck({})

  //
  const {tableProps, params, refresh, pagination} = useRequest(
    getPageData, {
      paginated: true,
      defaultPageSize: 10,
      formatResult
    }
  )

  const onSearch = (searchKey) => {
    params[0].searchKey = searchKey
    refresh().catch(e => message.error(`发生错误:${e.message}(${e.code})`))
  }

  const onDelete = (row) => {
    del(`/comments/${row.id}`).then((data) => {
      if (data) {
        message.success('删除评论成功')
        onSearch()
      }
    })
  }

  const onDeleteBatch = () => {
    if (ids != null) {
      del(`/comments/batch/${ids.join(',')}`)
        .then(d => {
          if (d) {
            message.success(`成功删除 ${ids.length} 条评论`)
            onSearch()
          }
        })
    }
  }

  return (
    <div className={'zr-panel'}>
      <div className={'zr-panel-header'}>
        <div>
          <PageHeader backIcon={<ArrowLeftOutlined/>}
                      onBack={() => window.history.back()} title={'用户评论'}
                      subTitle={`管理用户评论内容`}/>
        </div>
      </div>
      <div className={'ld2-list-page-box absolute'}>
        <div className={cs('ld2-query-box')} style={{paddingRight: '20px'}}>
          <SearchAutoComplete allowClear={true} onSelect={onSearch} placeholder={'请输入关键字查询'}/>
          <div style={{width: '10px'}}></div>
          <Button type={'primary'} className={'red'}
                  size={defaultSize}
                  onClick={onDeleteBatch}
                  disabled={ids.length < 1}>
            <LegacyIcon type={'delete'}/>
            批量删除
          </Button>
        </div>
        <div className={'ld2-table-box'}>
          <Table
            {...tableProps}
            pagination={{
              ...pagination,
              ...pageSetting
            }}
            rowSelection={rowSelection}
            rowKey={record => record.id}
            size={'middle'}
            columns={columns({onDelete})}/>
        </div>
      </div>
    </div>
  )
}

export default Comment